package com.IC.base.controller;

import IC.common.core.utils.file.FileTypeUtils;
import IC.system.api.domain.SysFile;
import com.IC.base.config.OssUtil;
import com.IC.base.config.OssUtil2;
import com.IC.base.service.ActualPopulationService;
import IC.common.core.domain.R;


import com.IC.base.util.ExcelUtils;

import com.IC.base.api.SixrealTovideopatrolService;

import com.IC.domain.PersonnelType;
import com.alibaba.nacos.common.utils.IoUtils;
import com.github.pagehelper.PageInfo;
import com.IC.domain.dto.ActualPopulationDTO;
import com.IC.domain.po.ActualPopulationPo;
import com.IC.domain.po.NationPO;
import com.IC.domain.vo.ActualPopulationVO;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

@RestController
@Log4j2
@RequestMapping("/population")
public class PopulationController {

    @Autowired
    private ActualPopulationService actualPopulationService;

    @Autowired
    private SixrealTovideopatrolService service;

    @Autowired
    private OssUtil ossUtil;

    @Autowired
    private RedisTemplate<String, Object> baseRedisTemplate;


    @PostMapping("/list")
    public R list(@RequestBody ActualPopulationDTO actualPopulationDTO) {
        PageInfo<ActualPopulationVO> findlist = actualPopulationService.findlist(actualPopulationDTO);
        return R.ok(findlist);
    }

    /**
     * 查询全部，存入es
     */
    @GetMapping("/all")
    public R list() {
        List<ActualPopulationVO> cachedData = actualPopulationService.all();
        return R.ok(cachedData);
    }

    /**
     * 人口迁移
     * @param id
     * @param pageNum
     * @param pageSize
     * @return
     */
    @PostMapping("/dotransfer")
    public R dotransfer(@RequestBody ActualPopulationVO actualPopulationVO){
        actualPopulationService.dotransfer(actualPopulationVO);
        return R.ok();
    }

    /**
     * 根据人口id查询人口信息
     * @param id
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/findById/{id}")
    public R findById(@PathVariable Integer id){
        ActualPopulationVO byId = actualPopulationService.findById(id);
        return R.ok(byId);
    }

    @GetMapping("/findByTenementId/{id}")
    public R findByTenementId(@PathVariable Integer id){
        List<ActualPopulationVO> byId = actualPopulationService.findByTenementId(id);
        return R.ok(byId);
    }

    @GetMapping("/findByPlotId")
    public R findByPlotId(@RequestParam("id") Integer id,@RequestParam(value = "pageNum", required = false) Integer pageNum,@RequestParam(value = "pageSize", required = false) Integer pageSize) {
        PageInfo<ActualPopulationVO> findlist = actualPopulationService.findByPlotId(id,pageNum,pageSize);
        return R.ok(findlist);
    }

    @GetMapping("/findByPlotIdList")
    public R findByPlotId(@RequestParam("id") Integer id) {
        List<ActualPopulationVO> findlist = actualPopulationService.findByPlotIdList(id);
        return R.ok(findlist);
    }

    @GetMapping("/findAll")
    public R findAll() {
        List<ActualPopulationPo> cachedData = (List<ActualPopulationPo>) baseRedisTemplate.opsForValue().get("ActualPopulation");
        if (cachedData == null) {
            cachedData = actualPopulationService.findAll();
            baseRedisTemplate.opsForValue().set("ActualPopulation", cachedData);
        }
        List<ActualPopulationPo> all = actualPopulationService.findAll();
        return R.ok(all);
    }

    @GetMapping("/list")
    public R get(){
        List<NationPO> nationList = (List<NationPO>) baseRedisTemplate.opsForValue().get("NationList");
        if(nationList == null){
            nationList = actualPopulationService.findNationList();
            baseRedisTemplate.opsForValue().set("NationList", nationList);
        }
        return R.ok(nationList);
    }


    @PostMapping("/add")
    public R add(@RequestBody ActualPopulationVO actualPopulationVO) {
        actualPopulationService.add(actualPopulationVO);
        refreshCache();
        String base64 = OssUtil2.imageUrlToBase64(actualPopulationVO.getPic());
        String imageBase64= base64.substring(20);
        service.recognizeFace(imageBase64);
        return R.ok();
    }

    @PostMapping("/update")
    public R update(@RequestBody ActualPopulationVO actualPopulationVO) {
        actualPopulationService.updateByPoId(actualPopulationVO);
        refreshCache();
        return R.ok();
    }

    @GetMapping("/delete/{id}")
    public R delete(@PathVariable("id")Long id) {
        actualPopulationService.removeById(id);
        refreshCache();
        return R.ok();
    }

    @PostMapping("/upload")
    public R<String> upload(@RequestParam("file") MultipartFile file){
        return R.ok(OssUtil.uploadMultipartFile(file));
    }

    @PostMapping("/import")
    public ResponseEntity<String> importUser(@RequestPart("file") MultipartFile file) {
        try {
            log.info("FILE"+file.getOriginalFilename());
            List<ActualPopulationPo> actualPopulationPos = ExcelUtils.readMultipartFile(file, ActualPopulationPo.class);
            // 执行批量插入操作
            actualPopulationService.insertList(actualPopulationPos);
            return ResponseEntity.ok("导入成功");
        } catch (Exception e) {
            log.error("导入失败: ", e);
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("导入失败: " + e.getMessage());
        }
    }


    @PostMapping("/export")
    public void export(HttpServletResponse response){
        List<ActualPopulationPo> list=actualPopulationService.selectlist();
        ExcelUtils.export(response,"实有人口",list,ActualPopulationPo.class);
    }

    @GetMapping("findPersonType")
    public R findPersonType(){
        PersonnelType personnelType=actualPopulationService.findPersonType();
        return R.ok(personnelType);
    }

    private void cacheAllData() {
        List<ActualPopulationPo> all = actualPopulationService.findAll();
        baseRedisTemplate.opsForValue().set("ActualPopulation", all);
    }

    @Scheduled(fixedRate = 10000) // 每10秒执行一次
    public void refreshCache() {
        cacheAllData();
    }


    @PostMapping("/findcount")
    public R findcount() {
        String maleCount=actualPopulationService.findcount();
        return R.ok(maleCount);
    }

    @PostMapping("/findlasttime")
    public R findlasttime(@RequestBody ActualPopulationDTO actualPopulationDTO) {
        List<ActualPopulationVO> findlasttime = actualPopulationService.findlasttime(actualPopulationDTO);
        return R.ok(findlasttime);
    }

    @GetMapping("findCount")
    public R findCount(){
        Integer findCount = actualPopulationService.findCount();
        return R.ok(findCount);
    }

    @GetMapping("findTodayAddCount")
    public R findTodayAddCount(){
        Integer findTodayAddCount = actualPopulationService.findTodayAddCount();
        return R.ok(findTodayAddCount);
    }





}
